package com.zhoug.common.modules.crash;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;


import com.zhoug.common.R;

import java.io.File;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Lifecycle;

/**
 * 异常详情页面
 *
 * @Author 35574
 * @Date 2020/6/18
 * @Description
 */
public class CrashDetailActivity extends AppCompatActivity {
    private static final String TAG = ">>>CrashDetailActivity";
    private String path;
    private TextView mTvTitle;
    private TextView mTvContent;
    private ProgressBar mProgressBar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.common_activity_crash_detail);
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            path = extras.getString("PATH");
        }
        findViews();
        if (path != null) {
            String name = new File(path).getName();
            int index = name.lastIndexOf(".");
            if (index >= 0) {
                name = name.substring(0, index);
            }
            mTvTitle.setText(name);
        }


        loadData();
    }

    private void findViews() {
        mTvTitle = findViewById(R.id.tv_title);
        mTvContent = findViewById(R.id.tv_content);
        mProgressBar = findViewById(R.id.progressBar);
    }

    /**
     * 获取文件中异常数据
     */
    private void loadData() {
        showProgress();
        new Thread(() -> {
            final String text = BaseUncaughtExceptionHandler.getInstance().getExceptionFromFile(path);
            if (getLifecycle().getCurrentState() != Lifecycle.State.DESTROYED) {
                runOnUiThread(() -> {
                    onLoadCallback(text);
                });
            } else {
                Log.e(TAG, "页面已销毁");
            }

        }).start();
    }

    /**
     * 结果监听
     *
     * @param text
     */
    private void onLoadCallback(String text) {
        dismissProgress();
        mTvContent.setText(text);
    }

    public void showProgress() {
        if (mProgressBar != null && mProgressBar.getVisibility() != View.VISIBLE) {
            mProgressBar.setVisibility(View.VISIBLE);
        }
    }


    public void dismissProgress() {
        if (mProgressBar != null && mProgressBar.getVisibility() != View.GONE) {
            mProgressBar.setVisibility(View.GONE);
        }
    }


}
